package edu.isquen.core.base.action;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.isquen.core.base.dao.DataPackage;
import edu.isquen.core.base.model.ValueObject;
import edu.isquen.core.base.service.BaseService;
import edu.isquen.core.user.model.User;

/****************************************************
* 文件名：BaseAction.java
* 文件描述：action基类
* 创建人： isquen, 2011 年6 月10 日
* 版本号：1.0
* 修改记录：
****************************************************/
public abstract class BaseAction<E> extends ActionSupport {

	private static final long serialVersionUID = 6142710641981991040L;
	private ParamsTable params;

	private ValueObject valObj = null;

	protected BaseService service = null;
	
	protected DataPackage<E> datas=null;
	
	protected String[] _selects=null;

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		return super.execute();
	}

	public BaseAction(BaseService service, ValueObject valObj) {
		this.service = service;
		this.valObj = valObj;
	}
	
	public String doNew(){
		return SUCCESS;
	}
	
	public String doSave() {
		try {
			if (this.valObj.getId() == null || this.valObj.getId().equals(""))
				service.doCreate(valObj);
			else
				service.doUpdate(valObj);

			this.addActionMessage("保存成功");
		} catch (Exception e) {
			this.addFieldError("1", e.getMessage());
			return INPUT;
		}
		return SUCCESS;
	}
	
	public String doEdit(){
		try {
			String key=this.getParams().getParameterAsString("id");
			ValueObject vo=service.doView(key);
			setValObj(vo);
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return SUCCESS;
	}

	public String doDelete() {
		try {
			service.doRemove(this.get_selects());
			addActionMessage("{*[delete.successful]*}");
		} catch (Exception e) {
			if (e.getMessage().indexOf("Could not execute JDBC batch update") > -1) {
				addFieldError("", "{*[Resource.has.been.cited]*}");
			} else {
				LOG.error(this.getClass().getName() + "doDelete", e);
				addFieldError("", e.getMessage());
			}
			return INPUT;
		}
		return SUCCESS;
	}
	
	@SuppressWarnings("unchecked")
	public String doList(){
		try {
			datas=(DataPackage<E>) service.doQuery();
		} catch (Exception e) {
			e.printStackTrace();
			return INPUT;
		}
		return SUCCESS;
	}
	
	
	public ParamsTable getParams() {
		if (params == null) {
			params = new ParamsTable();
			putRequestParameters();
			if (getSessionid() != null)
				params.setSessionid(getSessionid());
		}
		return params;
	}

	private void putRequestParameters() {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<?, ?> m = request.getParameterMap();
		String realPath = getSession().getServletContext().getRealPath("/");
		params.setParameter("realPath", realPath);
		params.setContextPath(request.getContextPath());
		Iterator<?> iter = m.keySet().iterator();
		while (iter.hasNext()) {
			String name = (String) iter.next();
			Object value = m.get(name);
			try {
				if (value instanceof String[])
					if (((String[]) value).length > 1)
						params.setParameter(name, value);
					else
						params.setParameter(name, ((String[]) value)[0]);
				else
					params.setParameter(name, value);
			} catch (Exception e) {
			}
		}
		params.setHttpRequest(request);
	}
	
	private HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}
	
	private HttpSession getSession() {
		return getRequest().getSession();
	}
	
	private String getSessionid() {
		return getSession().getId();
	}
	
	public static ActionContext getContext() {
		ActionContext context = ActionContext.getContext();
		return context;
	}
	
	public User getUser() throws Exception {
		Map session = getContext().getSession();
		User user = (User) session.get(User.front_USER);
		return user;
	}
	
	public void putIntoSession(String key, ValueObject obj) {
		// Map request = (Map)ActionContext.getContext().get("request");
		// request.put("books",books);
		Map<String, Object> session = ActionContext.getContext().getSession();
		session.put(key, obj);
	}
	
	public void removeFromSession(String key) {
		// Map request = (Map)ActionContext.getContext().get("request");
		// request.put("books",books);
		Map<String, Object> session = ActionContext.getContext()
				.getSession();
		session.remove(key);
	}
	
	public ValueObject getValObj() {
		return valObj;
	}

	public void setValObj(ValueObject valObj) {
		this.valObj = valObj;
	}
	
	public DataPackage<E> getDatas() {
		return datas;
	}

	public void setDatas(DataPackage<E> datas) {
		this.datas = datas;
	}
	
	public String[] get_selects() {
		return _selects;
	}

	public void set_selects(String[] selects) {
		_selects = selects;
	}
	
	public BaseService getService() {
		return service;
	}

	public void setService(BaseService service) {
		this.service = service;
	}
}
